﻿using System;
using Collab.Common;
using EnvDTE80;

namespace Collab.Modules.Session
{
    public class StateTracker : ObservableObject
    {
        protected DTE2 dte;

        private SessionState state;
        private EnvDTE.BuildEvents buildEvents;
        private EnvDTE.DebuggerEvents debuggerEvents;
        private EnvDTE.DTEEvents dteEvents;

        public SessionState SessionState
        {
            get { return this.state; }
            protected set 
            {
                if (this.state == value)
                    return;
                this.state = value;
                NotifyPropertyChanged("SessionState");
            }
        }


        public StateTracker(DTE2 dte)
        {
            if (dte == null)
                throw new ArgumentException("dte");
            this.dte = dte;
            this.buildEvents = this.dte.Events.BuildEvents;
            this.debuggerEvents = this.dte.Events.DebuggerEvents;
            this.dteEvents = this.dte.Events.DTEEvents;

            this.buildEvents.OnBuildBegin += BuildEvents_OnBuildBegin;
            this.buildEvents.OnBuildDone += BuildEvents_OnBuildDone;

            this.debuggerEvents.OnEnterRunMode += DebuggerEvents_OnEnterRunMode;
            this.debuggerEvents.OnEnterDesignMode += DebuggerEvents_OnEnterDesignMode;

            this.dteEvents.ModeChanged += new EnvDTE._dispDTEEvents_ModeChangedEventHandler(DteEvents_ModeChanged);
            

        }

        void DteEvents_ModeChanged(EnvDTE.vsIDEMode LastMode)
        {
            if (this.dte.Mode == EnvDTE.vsIDEMode.vsIDEModeDebug)
            {
                this.SessionState = Session.SessionState.Debugging;
            }
            else
            {
                if (LastMode == EnvDTE.vsIDEMode.vsIDEModeDebug)
                {
                    this.SessionState = Session.SessionState.Ready;
                }
            }
        }

        void DebuggerEvents_OnEnterDesignMode(EnvDTE.dbgEventReason reason)
        {
            this.SessionState = Session.SessionState.Ready;
        }

        void DebuggerEvents_OnEnterRunMode(EnvDTE.dbgEventReason reason)
        {
            this.SessionState = Session.SessionState.Debugging;

        }

        void BuildEvents_OnBuildDone(EnvDTE.vsBuildScope scope, EnvDTE.vsBuildAction action)
        {
            this.SessionState = Session.SessionState.Ready;
        }

        void BuildEvents_OnBuildBegin(EnvDTE.vsBuildScope scope, EnvDTE.vsBuildAction action)
        {
            this.SessionState = Session.SessionState.Building;
        }



    }
}
